package gohttp

import (
	"GoHttp/src/utils"
	"GoWeb/src/config"
	"fmt"
	"html/template"
	"io"
	"net/http"
	"os"
)

func MainRoute(w http.ResponseWriter, r *http.Request) (error) {
	r.ParseForm()
	t, err := template.ParseFiles(config.ViewRootPath + "login.html")
	if err != nil {
		return err
	}
	t.Execute(w, config.LocalIP)
	return nil
}
func uploadFile(w http.ResponseWriter, r *http.Request) (error) {
	r.ParseForm()
	values := r.Form
	groupType := values.Get("groupType")
	utils.Loge(groupType)
	if r.Method == "POST" {
		r.ParseMultipartForm(32 << 20)
		file, handel, err := r.FormFile("url")
		if err != nil {
			return err
		}
		defer file.Close()
		create, err := os.Create(handel.Filename)
		if err != nil {
			return err
		}
		defer create.Close()
		io.Copy(create, file)
		return NewResultData("上传成功")
	} else {
		return NewResultError(-1, "上传失败!").SetDebugMeg("不支持的请求方式")
	}

}
func Login(w http.ResponseWriter, r *http.Request) (error) {
	r.ParseForm()
	values := r.Form
	phone, pwd := values.Get("phone"), values.Get("pwd")
	if len(phone) == 0 || len(pwd) == 0 {
		return NewResultError(-1, "账号密码不能为空")
	}

	rows, err := db.Query(fmt.Sprintf("select 1 from user where phone = %s and pwd = %s limit 1;", phone, pwd))
	if err != nil {
		return err
	}
	if rows.Next() {
		return NewResultData("登陆成功")
	}
	return NewResultError(-1, "密码错误")
}
func Register(w http.ResponseWriter, r *http.Request) (error) {
	r.ParseForm()
	if r.Method == "GET" {
		t, err := template.ParseFiles(config.ViewRootPath + "register.html")
		if err != nil {
			return err
		}
		t.Execute(w, nil)
	} else {
		phone, name, pwd := r.Form.Get("phone"), r.Form.Get("name"), r.Form.Get("pwd")
		fmt.Printf("name:%s \n pwd:%s", name, pwd)
		if len(phone) == 0 {
			return NewResultError(-1, "账号不能为空")
		}
		if len(pwd) == 0 {
			return NewResultError(-1, "密码不能为空")
		}
		//if len(name) == 0 {
		//	return NewResultError(-1, "姓名不能为空")
		//}
		rows, err := db.Query(fmt.Sprintf("select 1 from user where phone = %s limit 1;", phone))
		if err != nil {
			return err
		}
		if rows.Next() {
			return NewResultError(-1, "账号已经存在")
		}

		result, err := db.Exec(fmt.Sprintf("INSERT INTO user (phone, pwd)VALUES(%s, %s);", phone, pwd))
		if err != nil {
			return err
		}
		line, err := result.RowsAffected()
		if err != nil {
			return err
		}
		if line == 1 {
			return NewResultData("注册成功")
		} else {
			return NewResultError(-1, "注册失败")
		}

	}

	return nil
}
